using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.IO.Compression;

namespace Common.Untils
{
    public class UpdateService
    {
        private readonly GiteeApi _giteeApi;
        private readonly string _currentVersion;
        private readonly string _updateTempPath;

        public UpdateService(string owner, string repo, string currentVersion, string accessToken = null)
        {
            _giteeApi = new GiteeApi(owner, repo, accessToken);
            _currentVersion = currentVersion;
            _updateTempPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "SanmaoTools",
                "Updates"
            );
        }

        public async Task<(bool hasUpdate, string newVersion, string updateInfo)> CheckForUpdatesAsync()
        {
            try
            {
                var latestRelease = await _giteeApi.GetLatestReleaseAsync();
                var latestVersion = latestRelease.TagName.TrimStart('v');

                bool hasUpdate = Version.Parse(latestVersion) > Version.Parse(_currentVersion);
                return (hasUpdate, latestVersion, latestRelease.Body);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"检查更新失败: {ex.Message}");
                throw;
            }
        }

        public async Task DownloadAndInstallUpdateAsync(IProgress<(long current, long total)> progress = null)
        {
            string updateFilePath = string.Empty;
            string updateInfoPath = string.Empty;
            string batchPath = string.Empty;
            string extractPath = string.Empty;

            try
            {
                // 获取应用程序目录的完整路径
                string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
                string exePath = Path.Combine(appDirectory, "SanmaoTools.exe");

                var release = await _giteeApi.GetLatestReleaseAsync();
                if (release.Assets == null || release.Assets.Length == 0)
                {
                    throw new Exception("未找到更新包");
                }

                var updatePackage = release.Assets[0];
                var updateBytes = await _giteeApi.DownloadReleaseAssetAsync(updatePackage.BrowserDownloadUrl, progress);

                // 确保临时目录存在
                Directory.CreateDirectory(_updateTempPath);

                // 保存更新包
                updateFilePath = Path.Combine(_updateTempPath, updatePackage.Name);
                await File.WriteAllBytesAsync(updateFilePath, updateBytes);

                // 创建解压目录
                extractPath = Path.Combine(_updateTempPath, "extracted");
                if (Directory.Exists(extractPath))
                {
                    Directory.Delete(extractPath, true);
                }
                Directory.CreateDirectory(extractPath);

                // 解压更新包
                ZipFile.ExtractToDirectory(updateFilePath, extractPath);

                // 保存更新包路径到文件，供更新后删除
                updateInfoPath = Path.Combine(_updateTempPath, "update_info.txt");
                await File.WriteAllTextAsync(updateInfoPath, updateFilePath);


                // 将批处理文件保存到临时目录
                batchPath = Path.Combine(_updateTempPath, "update.bat");

                // 创建更新批处理文件 - 使用简单的ASCII字符
                string batchContent = @$"@echo off
echo Updating application...
timeout /t 3 /nobreak
taskkill /f /im SanmaoTools.exe 2>nul
timeout /t 2 /nobreak

echo Copying files...
xcopy ""{Path.Combine(extractPath, "net8.0-windows")}\*"" ""{appDirectory}"" /E /Y /I

echo Cleaning up...
cd /d ""{_updateTempPath}""
if exist ""extracted"" rd /s /q ""extracted""
if exist ""{Path.GetFileName(updateFilePath)}"" del /f /q ""{Path.GetFileName(updateFilePath)}""
if exist ""update_info.txt"" del /f /q ""update_info.txt""
cd /d ""{appDirectory}""

echo Update complete!
start """" ""{exePath}""
del ""%~f0""";

                await File.WriteAllTextAsync(batchPath, batchContent);

//                // 创建一个启动器批处理文件，用于启动更新批处理
//                string launcherPath = Path.Combine(Path.GetTempPath(), "update_launcher.bat");
//                string launcherContent = @$"@echo off
//start """" /wait ""{batchPath}""
//del ""%~f0""";

               // await File.WriteAllTextAsync(launcherPath, launcherContent);

                // 执行启动器批处理
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = batchPath,
                    UseShellExecute = true,
                    CreateNoWindow = true,
                    WindowStyle = ProcessWindowStyle.Hidden
                };

                Process.Start(startInfo);
                // 保存新版本号
                VersionInfo.Save(release.TagName.TrimStart('v'));

                // 关闭当前应用程序
                Application.Current.Shutdown();
            }
            catch (Exception ex)
            {
                // 如果下载或保存过程中出错，清理已下载的文件
                if (!string.IsNullOrEmpty(updateFilePath) && File.Exists(updateFilePath))
                {
                    try { File.Delete(updateFilePath); } catch { }
                }
                if (!string.IsNullOrEmpty(extractPath) && Directory.Exists(extractPath))
                {
                    try { Directory.Delete(extractPath, true); } catch { }
                }
                if (!string.IsNullOrEmpty(updateInfoPath) && File.Exists(updateInfoPath))
                {
                    try { File.Delete(updateInfoPath); } catch { }
                }
                if (!string.IsNullOrEmpty(batchPath) && File.Exists(batchPath))
                {
                    try { File.Delete(batchPath); } catch { }
                }

                Debug.WriteLine($"下载更新失败: {ex.Message}");
                throw;
            }
        }
    }
}